package com.wutongyu.mannyburger;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class UserDatabaseHelper extends SQLiteOpenHelper {

    private static final String TAG = "UserDatabaseHelper";
    private static final String DATABASE_NAME = "users.db";
    private static final int DATABASE_VERSION = 4; // 升级版本号以添加性别字段

    public static final String TABLE_USERS = "users";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_PHONE = "phone_number";
    public static final String COLUMN_PASSWORD = "password"; // 存储哈希密码
    // 新增字段
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_ADDRESS = "address";
    public static final String COLUMN_AVATAR_ID = "avatar_id";
    // 密保问题字段
    public static final String COLUMN_SECURITY_QUESTION = "security_question";
    public static final String COLUMN_SECURITY_ANSWER = "security_answer";
    // 性别字段
    public static final String COLUMN_GENDER = "gender";

    // 创建表的 SQL 语句
    private static final String TABLE_CREATE =
            "CREATE TABLE " + TABLE_USERS + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_PHONE + " TEXT UNIQUE NOT NULL, " +
                    COLUMN_PASSWORD + " TEXT NOT NULL, " +
                    COLUMN_USERNAME + " TEXT, " +
                    COLUMN_ADDRESS + " TEXT, " +
                    COLUMN_AVATAR_ID + " INTEGER, " +
                    COLUMN_SECURITY_QUESTION + " INTEGER, " +
                    COLUMN_SECURITY_ANSWER + " TEXT, " +
                    COLUMN_GENDER + " TEXT DEFAULT '男');";

    public UserDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i(TAG, "创建用户数据库表: " + TABLE_CREATE);
        db.execSQL(TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "升级数据库，将添加新列。版本从 " + oldVersion + " 到 " + newVersion);
        // 保留旧数据并添加新列
        if (oldVersion == 1 && newVersion >= 2) {
            db.execSQL("ALTER TABLE " + TABLE_USERS + " ADD COLUMN " + COLUMN_USERNAME + " TEXT;");
            db.execSQL("ALTER TABLE " + TABLE_USERS + " ADD COLUMN " + COLUMN_ADDRESS + " TEXT;");
            db.execSQL("ALTER TABLE " + TABLE_USERS + " ADD COLUMN " + COLUMN_AVATAR_ID + " INTEGER;");
        }
        
        if (oldVersion <= 2 && newVersion >= 3) {
            db.execSQL("ALTER TABLE " + TABLE_USERS + " ADD COLUMN " + COLUMN_SECURITY_QUESTION + " INTEGER;");
            db.execSQL("ALTER TABLE " + TABLE_USERS + " ADD COLUMN " + COLUMN_SECURITY_ANSWER + " TEXT;");
        }
        
        if (oldVersion <= 3 && newVersion >= 4) {
            db.execSQL("ALTER TABLE " + TABLE_USERS + " ADD COLUMN " + COLUMN_GENDER + " TEXT DEFAULT '男';");
        }
    }

    /**
     * 添加新用户
     * @param phone 手机号
     * @param password 密码 (明文)
     * @param securityQuestion 密保问题ID
     * @param securityAnswer 密保答案
     * @return 如果添加成功返回 true, 如果手机号已存在返回 false
     */
    public boolean addUser(String phone, String password, int securityQuestion, String securityAnswer) {
        if (isUserExists(phone)) {
            Log.w(TAG, "尝试添加用户失败，手机号已存在: " + phone);
            return false; // 用户已存在
        }
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_PHONE, phone);
        values.put(COLUMN_PASSWORD, hashPassword(password)); // 存储哈希密码
        values.put(COLUMN_SECURITY_QUESTION, securityQuestion);
        values.put(COLUMN_SECURITY_ANSWER, securityAnswer);
        
        // 添加随机头像ID
        int randomAvatarId = getRandomAvatarId();
        values.put(COLUMN_AVATAR_ID, randomAvatarId);
        Log.i(TAG, "为新用户分配随机头像ID: " + randomAvatarId);

        long result = db.insert(TABLE_USERS, null, values);
        db.close();

        if (result == -1) {
            Log.e(TAG, "添加用户时发生错误: " + phone);
            return false; // 插入失败
        } else {
            Log.i(TAG, "成功添加用户: " + phone);
            return true; // 插入成功
        }
    }

    /**
     * 添加新用户（兼容旧版本，不包含密保问题）
     * @param phone 手机号
     * @param password 密码 (明文)
     * @return 如果添加成功返回 true, 如果手机号已存在返回 false
     */
    public boolean addUser(String phone, String password) {
        return addUser(phone, password, -1, "");
    }

    /**
     * 获取用户信息
     * @param phone 手机号
     * @return 包含用户信息的ContentValues对象，如果用户不存在则返回null
     */
    @SuppressLint("Range")
    public ContentValues getUserInfo(String phone) {
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_PHONE + " = ?";
        String[] selectionArgs = { phone };

        Cursor cursor = db.query(TABLE_USERS, null, selection, selectionArgs, null, null, null);
        ContentValues userInfo = null;

        if (cursor != null && cursor.moveToFirst()) {
            userInfo = new ContentValues();
            userInfo.put(COLUMN_ID, cursor.getInt(cursor.getColumnIndex(COLUMN_ID)));
            userInfo.put(COLUMN_PHONE, cursor.getString(cursor.getColumnIndex(COLUMN_PHONE)));
            
            // 获取新增字段，需要处理可能为空的情况
            if (cursor.getColumnIndex(COLUMN_USERNAME) != -1) {
                userInfo.put(COLUMN_USERNAME, cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
            }
            if (cursor.getColumnIndex(COLUMN_ADDRESS) != -1) {
                userInfo.put(COLUMN_ADDRESS, cursor.getString(cursor.getColumnIndex(COLUMN_ADDRESS)));
            }
            if (cursor.getColumnIndex(COLUMN_AVATAR_ID) != -1) {
                userInfo.put(COLUMN_AVATAR_ID, cursor.getInt(cursor.getColumnIndex(COLUMN_AVATAR_ID)));
            }
            
            // 获取密保问题和答案字段
            if (cursor.getColumnIndex(COLUMN_SECURITY_QUESTION) != -1) {
                userInfo.put(COLUMN_SECURITY_QUESTION, cursor.getInt(cursor.getColumnIndex(COLUMN_SECURITY_QUESTION)));
            }
            if (cursor.getColumnIndex(COLUMN_SECURITY_ANSWER) != -1) {
                userInfo.put(COLUMN_SECURITY_ANSWER, cursor.getString(cursor.getColumnIndex(COLUMN_SECURITY_ANSWER)));
            }
            
            // 获取性别字段
            if (cursor.getColumnIndex(COLUMN_GENDER) != -1) {
                userInfo.put(COLUMN_GENDER, cursor.getString(cursor.getColumnIndex(COLUMN_GENDER)));
            }
            
            cursor.close();
        }
        db.close();
        return userInfo;
    }

    /**
     * 更新用户信息
     * @param phone 手机号（用作标识符）
     * @param username 用户名
     * @param address 地址
     * @param avatarId 头像ID
     * @return 更新是否成功
     */
    public boolean updateUserInfo(String phone, String username, String address, int avatarId) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        
        values.put(COLUMN_USERNAME, username);
        values.put(COLUMN_ADDRESS, address);
        values.put(COLUMN_AVATAR_ID, avatarId);
        
        String whereClause = COLUMN_PHONE + " = ?";
        String[] whereArgs = { phone };
        
        int rowsAffected = db.update(TABLE_USERS, values, whereClause, whereArgs);
        db.close();
        
        return rowsAffected > 0;
    }
    
    /**
     * 更新用户地址
     * @param phone 手机号
     * @param address 新地址
     * @return 更新是否成功
     */
    public boolean updateUserAddress(String phone, String address) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_ADDRESS, address);
        
        String whereClause = COLUMN_PHONE + " = ?";
        String[] whereArgs = { phone };
        
        int rowsAffected = db.update(TABLE_USERS, values, whereClause, whereArgs);
        db.close();
        
        return rowsAffected > 0;
    }

    /**
     * 检查用户是否存在且密码是否匹配
     * @param phone 手机号
     * @param password 密码 (明文)
     * @return 如果验证成功返回 true, 否则返回 false
     */
    public boolean checkUser(String phone, String password) {
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_PHONE + " = ?";
        String[] selectionArgs = { phone };

        Cursor cursor = db.query(TABLE_USERS, new String[]{COLUMN_PASSWORD}, selection, selectionArgs, null, null, null);

        boolean passwordMatch = false;
        if (cursor != null && cursor.moveToFirst()) {
            String storedPassword = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PASSWORD));
            // 比较哈希密码
            if (password != null && verifyPassword(password, storedPassword)) {
                passwordMatch = true;
            }
            cursor.close();
        }
        db.close();

        if (passwordMatch) {
            Log.i(TAG, "用户验证成功: " + phone);
        } else {
            Log.w(TAG, "用户验证失败: " + phone);
        }
        return passwordMatch;
    }

    /**
     * 检查指定手机号的用户是否已存在
     * @param phone 手机号
     * @return 如果存在返回 true, 否则返回 false
     */
    public boolean isUserExists(String phone) {
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_PHONE + " = ?";
        String[] selectionArgs = { phone };

        Cursor cursor = db.query(TABLE_USERS, new String[]{COLUMN_ID}, selection, selectionArgs, null, null, null);
        boolean exists = (cursor != null && cursor.getCount() > 0);
        if (cursor != null) {
            cursor.close();
        }
        db.close();

        if (exists) {
            Log.d(TAG, "手机号已存在: " + phone);
        } else {
            Log.d(TAG, "手机号不存在: " + phone);
        }
        return exists;
    }

    /**
     * 将密码进行SHA-256哈希处理
     * @param password 原始密码
     * @return 哈希后的密码字符串
     */
    private String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(password.getBytes());
            byte[] bytes = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "哈希密码时出错", e);
            // 如果无法使用SHA-256，则退回到简单的替代方案（不推荐在生产环境中使用）
            return password + "_hashed";
        }
    }

    /**
     * 验证密码是否匹配
     * @param enteredPassword 用户输入的密码
     * @param storedHash 存储的哈希密码
     * @return 如果密码匹配返回true，否则返回false
     */
    private boolean verifyPassword(String enteredPassword, String storedHash) {
        String hashedEnteredPassword = hashPassword(enteredPassword);
        return hashedEnteredPassword.equals(storedHash);
    }

    /**
     * 检查用户的密保问题答案是否正确
     * @param phone 手机号
     * @param securityAnswer 用户输入的密保答案
     * @return 如果答案正确返回true，否则返回false
     */
    public boolean checkSecurityAnswer(String phone, String securityAnswer) {
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_PHONE + " = ?";
        String[] selectionArgs = { phone };

        Cursor cursor = db.query(TABLE_USERS, new String[]{COLUMN_SECURITY_ANSWER}, selection, selectionArgs, null, null, null);

        boolean answerMatch = false;
        if (cursor != null && cursor.moveToFirst()) {
            String storedAnswer = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_SECURITY_ANSWER));
            // 比较密保答案（不区分大小写）
            if (securityAnswer != null && storedAnswer != null && 
                securityAnswer.trim().toLowerCase().equals(storedAnswer.trim().toLowerCase())) {
                answerMatch = true;
            }
            cursor.close();
        }
        db.close();

        return answerMatch;
    }

    /**
     * 获取用户的密保问题ID
     * @param phone 手机号
     * @return 密保问题ID，如果用户不存在或没有设置密保问题则返回-1
     */
    public int getSecurityQuestion(String phone) {
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_PHONE + " = ?";
        String[] selectionArgs = { phone };

        Cursor cursor = db.query(TABLE_USERS, new String[]{COLUMN_SECURITY_QUESTION}, selection, selectionArgs, null, null, null);

        int questionId = -1;
        if (cursor != null && cursor.moveToFirst()) {
            questionId = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_SECURITY_QUESTION));
            cursor.close();
        }
        db.close();

        return questionId;
    }

    /**
     * 重置用户密码
     * @param phone 手机号
     * @param newPassword 新密码
     * @return 如果重置成功返回true，否则返回false
     */
    public boolean resetPassword(String phone, String newPassword) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_PASSWORD, hashPassword(newPassword));
        
        String whereClause = COLUMN_PHONE + " = ?";
        String[] whereArgs = { phone };
        
        int rowsAffected = db.update(TABLE_USERS, values, whereClause, whereArgs);
        db.close();
        
        return rowsAffected > 0;
    }

    /**
     * 更新用户性别
     * @param phone 手机号
     * @param gender 性别
     * @return 更新是否成功
     */
    public boolean updateUserGender(String phone, String gender) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_GENDER, gender);
        
        String whereClause = COLUMN_PHONE + " = ?";
        String[] whereArgs = { phone };
        
        int rowsAffected = db.update(TABLE_USERS, values, whereClause, whereArgs);
        db.close();
        
        return rowsAffected > 0;
    }
    
    /**
     * 更新用户完整信息，包括性别
     * @param phone 手机号（用作标识符）
     * @param username 用户名
     * @param address 地址
     * @param avatarId 头像ID
     * @param gender 性别
     * @return 更新是否成功
     */
    public boolean updateUserFullInfo(String phone, String username, String address, int avatarId, String gender) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        
        values.put(COLUMN_USERNAME, username);
        values.put(COLUMN_ADDRESS, address);
        values.put(COLUMN_AVATAR_ID, avatarId);
        values.put(COLUMN_GENDER, gender);
        
        String whereClause = COLUMN_PHONE + " = ?";
        String[] whereArgs = { phone };
        
        int rowsAffected = db.update(TABLE_USERS, values, whereClause, whereArgs);
        db.close();
        
        return rowsAffected > 0;
    }

    /**
     * 获取随机头像ID (1-4)
     * @return 返回随机头像资源ID，对应avatar_custom_1到avatar_custom_4
     */
    private int getRandomAvatarId() {
        Random random = new Random();
        // 生成1到4之间的随机整数
        int randomNum = random.nextInt(4) + 1;
        
        // 将随机数转换为实际资源ID
        int resourceId;
        switch (randomNum) {
            case 1:
                resourceId = R.drawable.avatar_custom_1;
                break;
            case 2:
                resourceId = R.drawable.avatar_custom_2;
                break;
            case 3:
                resourceId = R.drawable.avatar_custom_3;
                break;
            case 4:
                resourceId = R.drawable.avatar_custom_4;
                break;
            default:
                resourceId = R.drawable.avatar_custom_1;
                break;
        }
        
        return resourceId;
    }
} 